import os
import cv2
import numpy as np

#脸部检测函数
def face_detect_demo(image):
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    faces = face_detector.detectMultiScale(gray, 1.2, 6)
    #未检测到面部返回原始图像
    if (len(faces) == 0):
        return None,None
    #假设只有一张脸，xy为左上角坐标，wh为矩形宽高
    (x,y,w,h) = faces[0]
    return gray[y:y + w,x:x + h], faces[0]
def ReFileName(dirPath):
    """
    :param dirPath: 文件夹路径
    :return:
    """
    # 对目录下的文件进行遍历
    faces = []
    for file in os.listdir(dirPath):
        if os.path.isfile(os.path.join(dirPath,file)) == True:
            c = os.path.basename(file)
            name = dirPath + '\\' + c
            img = cv2.imread(name)
            #检测脸部
            face, rect = face_detect_demo(img)
            #忽略未检测到的脸部
            if face is not None:
                faces.append(face)
    cv2.waitKey(1)
    cv2.destroyAllWindows()
    return faces
#一号人物照片读取
dirPathone = r"D:\python_pycharm\project1\one"#文件路径
LiuYifei = ReFileName(dirPathone)
labelLiuYifei = np.array([0 for i in range(len(LiuYifei))])#标签处理
#二号人物照片读取
dirPathtwo = r"D:\python_pycharm\project1\two"#文件路径
YangMi = ReFileName(dirPathtwo)
lableYangMi = np.array([1 for i in range(len(YangMi))])#标签处理
#拼接并打乱数据特征和标签
x = np.concatenate((LiuYifei,YangMi),axis=0)
y= np.concatenate((labelLiuYifei,lableYangMi),axis=0)
index = [i for i in range(len(y))]
np.random.seed(1)
np.random.shuffle(index)
train_data = x[index]
train_label = y[index]
#分类器
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.train(train_data, train_label)
#保存训练数据
recognizer.write('train.yml')

